/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.agent.service;

import cn.ac.iie.agent.tools.PropsFiles;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;

/**
 *
 * @author dell
 */
public class FtpUploadService {

    private static Logger logger = Logger.getLogger(FtpUploadService.class);

    public static Map<String, String> execute(String xml, Map<String, String> rsMap, String subjobid) {

        //本地上传路径
         PropsFiles ps = new PropsFiles();
        String uploadFilePathRoot = ps.getValue("uploadFilePathRoot");
        if (!uploadFilePathRoot.endsWith("/")) {
            uploadFilePathRoot = uploadFilePathRoot + "/";
        }
        logger.info(subjobid + " the uploadFilePathRoot is: " + uploadFilePathRoot);
        String namespace = ps.getValue("namespace");

        String localFilePath = uploadFilePathRoot + ps.getValue("uploadType") + "/" + namespace + "/";
        String localErrorPath = uploadFilePathRoot + ps.getValue("downloadType") + "/" + namespace + "/" + ps.getValue("ErrorType") + "/";
        logger.info(subjobid + " the namespace is: " + namespace + " and the localFilePath is: " + localFilePath + " and the localErrorPath is: " + localErrorPath);

        //读取本地localFilePath下Ctrl所有JSON文件
        File ctrlDir = new File(localFilePath + "Ctrl");
        if (!ctrlDir.exists()) {
            logger.info(subjobid + " the local JSON file path does not exist.");
            rsMap.put("status", "fail");
            rsMap.put("desc", "ftpupload execute unsuccessfully! Cause the " + localFilePath + "Ctrl does not exist!");
            rsMap.put("total", "0");
            rsMap.put("complete", "0");
        } else {
            List<String> jsonreturnFlag = new ArrayList<String>();//一个json文件处理结果
            String realnamespace = namespace.substring(namespace.indexOf("_") + 1, namespace.length());
            int allInt = 0;
            int succInt = 0;

            File[] ctrlFiles = ctrlDir.listFiles();
            logger.info(subjobid + " the path of： " + localFilePath + "Ctrl has " + ctrlFiles.length + " files.");
            List<File> okList = new ArrayList<File>();
            List<File> dataList = new ArrayList<File>();
            List<File> dwdList = new ArrayList<File>();
            for (int i = 0; i < ctrlFiles.length; i++) {
                if (ctrlFiles[i].getName().endsWith(".ok")) {
                    okList.add(ctrlFiles[i]);
                } else if (ctrlFiles[i].getName().endsWith(".dwd")) {
                    dwdList.add(ctrlFiles[i]);
                } else {
                    dataList.add(ctrlFiles[i]);
                }
            }

            //起线程，一个JSON一个任务
            ThreadPoolExecutor threadPool = new ThreadPoolExecutor(2, 4, 3,
                    TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(dataList.size()),
                    new ThreadPoolExecutor.DiscardOldestPolicy());

            for (int i = 0; i < dataList.size(); i++) {
                String tmpokname = dataList.get(i).getName() + ".ok";
                for (int j = 0; j < okList.size(); j++) {
                    if (tmpokname.equals(okList.get(j).getName())) {
                        boolean existflag = false;
                        for (int k = 0; k < dwdList.size(); k++) {
                            String tmpdwdname = dataList.get(i).getName() + "." + realnamespace + ".dwd";
                            if (tmpdwdname.equals(dwdList.get(k).getName())) {
                                existflag = true;
                                break;
                            }
                        }
                        if (!existflag) {
                            logger.info(subjobid + " start to analyze the JSON file and upload the data files by JSON file: " + dataList.get(i).getName() + " and the CtrlPath is " + localFilePath + "Ctrl ,the DataPath is " + localFilePath + "Data");
                            //解析json文件，上传数据文件（若失败，写失败json文件)
                            allInt++;
                            threadPool.execute(new FtpUploadJsonFilesThread(subjobid, jsonreturnFlag, dataList.get(i).getName(), localFilePath, localErrorPath, realnamespace));
                        }
                    }
                }
            }

            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
            }
            while (true) {//直至所有线程结束，才继续
                int activeThread = threadPool.getActiveCount();
                if (activeThread == 0) {
                    break;
                } else {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException ex) {
                        logger.error(ex.getMessage(), ex);
                    }
                }
            }
            threadPool.shutdown();

            if (!jsonreturnFlag.isEmpty()) {
                String result = "";
                for (String f : jsonreturnFlag) {
                    if ("true".equals(f)) {
                        succInt++;
                    }
                    result += f + ",";
                }
                if (!result.contains("false")) {
                    rsMap.put("status", "success");
                    rsMap.put("desc", "ftpupload execute successfully!");
                    rsMap.put("total", allInt + "");
                    rsMap.put("complete", succInt + "");
                } else if (!result.contains("true")) {
                    rsMap.put("status", "fail");
                    rsMap.put("desc", "ftpupload execute unsuccessfully!");
                    rsMap.put("total", allInt + "");
                    rsMap.put("complete", succInt + "");
                } else if (result.contains("true") && result.contains("false")) {
                    rsMap.put("status", "half-success");
                    rsMap.put("desc", "ftpupload half success!");
                    rsMap.put("total", allInt + "");
                    rsMap.put("complete", succInt + "");
                }
            }
        }
        return rsMap;
    }
}
